package com.zsy;

import com.alibaba.fastjson.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class ParseXml {

    public static Map parseData(Document dom) {
        Map<String, Object> result = new HashMap<>();
        Element root = dom.getRootElement();
        List<Element> lines = root.elements("line");
        List<Map<String, Object>> lineList = new LinkedList<>();
        for (Element line : lines) {
            Map<String, Object> lineMap = new HashMap<>();
            lineMap.put("lineCode", line.attribute("lineCode").getText());
            lineMap.put("lineName", line.attribute("lineName").getText());
            lineMap.put("country", line.attribute("country").getText());

            Map<String, Object> teamMap = new HashMap<>();
            Element team = line.element("team");
            List<Element> teamDatas = team.elements("teamData");
            Element ll = teamDatas.get(0);
            Iterator iterator = ll.attributeIterator();
            int i = 0;
            while (iterator.hasNext()) {
                i++;
                Attribute o = (Attribute) iterator.next();
                System.out.println(o.getName() + "==" + o.getValue());
            }
            System.out.println(i);
            List<Map<String, Object>> teamDataList = new LinkedList<>();

            teamMap.put("teamData", teamDataList);
            lineMap.put("team", teamMap);
            lineList.add(lineMap);

        }
        result.put("lines", lineList);
        return result;
    }

    public static void parseDate2(Document dom) throws IOException {
        Element root = dom.getRootElement();
        Map o = Xml2Json.iterateElement(root);
        JSONObject json= new JSONObject(o);
        System.out.println(((List)o.get("line")).get(1));
//        FileWriter writer=new FileWriter("E:\\石油商城\\abc.txt");
//        writer.write(json.toJSONString());
//        writer.flush();
//        writer.close();
    }

    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader read = new SAXReader();
        //把xml文档加载到document对象中
        File f = new File("E:\\石油商城\\index.xml");
        Document doc = read.read(f);
        parseDate2(doc);
        //System.out.println(r);
    }
}
